package com.fas.core.plugin.shiro.kit;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import com.fas.hehe.system.model.User;

public class PasswordKit {
	private static PasswordKit me = new PasswordKit();

	private PasswordKit() {
	}

	public static PasswordKit me() {
		return me;
	}

	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

	private String algorithmName = "md5";
	private int hashIterations = 2;

	public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
		this.randomNumberGenerator = randomNumberGenerator;
	}

	public void setAlgorithmName(String algorithmName) {
		this.algorithmName = algorithmName;
	}

	public void setHashIterations(int hashIterations) {
		this.hashIterations = hashIterations;
	}

	public User encryptPassword(User user) {

		user.setSalt(randomNumberGenerator.nextBytes().toHex());

		String newPassword = new SimpleHash(algorithmName, user.getPassword(), ByteSource.Util.bytes(user
				.getCredentialsSalt()), hashIterations).toHex();

		user.setPassword(newPassword);
		return user;
	}

	public String createPwd(String newPassword, String gredentialsSalt) {
		return new SimpleHash(algorithmName, newPassword, ByteSource.Util.bytes(gredentialsSalt), hashIterations)
				.toHex();
	}

	
	public String randomPassword() {
		final String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		char[] rands = new char[6];
		for (int i = 0; i < rands.length; i++) {
			int rand = (int) (Math.random() * str.length());
			rands[i] = str.charAt(rand);
		}
		return new String(rands);
	}
	
	public static void main(String[] args) {
		System.out.println(PasswordKit.me().randomPassword());
	}
}
